package com.android.antelopeapp.view.BeautyPic;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.antelopeapp.R;
import com.lyhw.model.ImageTag;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Created by phk on 2014/12/29.
 */
public class TagableImage extends FrameLayout {
    /**
     * 普通模式
     */
    public static final int NORMAL_MODE = 0;
    /**
     * 交互模式
     */
    private int mInteractModel = NORMAL_MODE;
    /**
     * 编辑模式
     */
    public static final int EDIT_MODE = 1;
    public final String TAG = "TagableImage";
    /**
     * 标签实例列表
     */
    private List<ImageTag> mTags = new ArrayList<>();
    /**
     * 标签控件列表
     */
    private List<ImageTagBox> mTagBoxes = new ArrayList<>();
    /**
     * 背景图片控件
     */
    private ImageView mImage;

    /**
     * bmp
     * */
    private Bitmap mBmp;
     /**
     * 标签容器
     */

    private FrameLayout mTagContainer;
    /**
     * 是否处理touch事件
     */
    private boolean mIsTouchable = true;
    private boolean mAddTagEnable = true;

    /**
     * 点击事件的监听器 内部使用
     * 为编辑模式和普通模式统一监听接口
     */
    private OnTagClickListener mOnTagClickListener;
    /**
     * 点击事件的监听器 外部使用
     * 将会在执行内部监听函数最后执行
     */
    private OnTagClickListener mOnTagClickListenerOpen;
    /**
     * 添加标签的监听器
     */
    private OnAddTagBoxListener mOnAddTagBoxListener;
    /**
     * 删除标签控件的监听器
     */
    private OnDelTagBoxListener mOnDelTagBoxListener;

    private boolean mTagsEnableMove = false;

    private GestureDetector gestureDetector;

    /**
     * 标签不能马上添加，需要在tagcontainer高宽度大小固定之后才能添加，因此采用队列的方式进行处理。
     * 需要添加的标签的队列
     * */
    private Queue<ImageTagBox> tagBoxQueue = new LinkedList<>();
    /**handler用于处理添加tagbox事件*/
    private Handler tagQueHandler;

    public static enum MSG{ADDTAG,FORBID_ADDTAG}

    private int msgInt = 50;//50ms

    public TagableImage(Context context) {
        this(context, null);
    }
    public TagableImage(Context context, AttributeSet attrs) {
        super(context, attrs);

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.view_tagimage, this, true);

        mImage = (ImageView) getChildAt(0);

        mTagContainer = (FrameLayout) getChildAt(1);

        tagQueHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if(msg.what == MSG.ADDTAG.ordinal()) {
                    if (mTagContainer.getWidth() == 0 || mTagContainer.getHeight() == 0) {
                        if (!tagBoxQueue.isEmpty()) {
                            tagQueHandler.sendEmptyMessageDelayed(MSG.ADDTAG.ordinal(), msgInt);
                        }
                    } else {
                        int len = tagBoxQueue.size();
                        for (int i = 0; i < len; i++) {
                            ImageTagBox tagbox = tagBoxQueue.poll();
                            //如果是隐藏标签，表示该标签属于刚翻转尚未调整
                            if (tagbox.getVisibility() == INVISIBLE) {
                                //如果标签的宽度未知，则继续加入队列
                                if (tagbox.getTextWidth() == 0) {
                                    tagBoxQueue.add(tagbox);
                                } else {
                                    //否则更新布局参数
                                    tagbox.updateLayoutParam();
                                    tagbox.requestLayout();
                                    tagbox.setVisibility(VISIBLE);
                                }
                            }
                            if (tagbox.getParent() != mTagContainer) {
                                tagbox.updatePos(mTagContainer);
                                mTagContainer.addView(tagbox);
                            }
                        }
                        //如果队列非空，则继续等待
                        if (!tagBoxQueue.isEmpty()) {
                            tagQueHandler.sendEmptyMessageDelayed(MSG.ADDTAG.ordinal(), msgInt);
                        }
                    }
                }else if(msg.what == MSG.FORBID_ADDTAG.ordinal()){
                    if(!mAddTagEnable){
                        mAddTagEnable = true;
                    }
                }
                return true;
            }
        });
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(gestureDetector != null) {
            gestureDetector.onTouchEvent(event);
        }
        return true;
    }

    /**清空队列*/
    public void clearTagQueue(){
        tagBoxQueue.clear();
    }
    /**加入队列*/
    public void addToTagQueue(ImageTagBox tagbox){
        tagBoxQueue.add(tagbox);
        tagQueHandler.sendEmptyMessageDelayed(MSG.ADDTAG.ordinal(),msgInt);
    }

    public List<ImageTag> getmTags() {
        return mTags;
    }

    public int getmInteractModel() {
        return mInteractModel;
    }

    public void setmInteractModel(int mInteractModel) {
        this.mInteractModel = mInteractModel;

        //在添加标签时，会自动给标签添加事件处理器，这里对原有的tagbox进行修改
        for(ImageTagBox tagbox: mTagBoxes){
            tagbox.setmGestureDetector(createDefTagGesDector(tagbox));
        }

        switch (mInteractModel) {
            case NORMAL_MODE:
                //普通模式下
                //标签不能移动
                setTagsEnableMove(false);
                //点击空白位置，将会隐藏标签层
                gestureDetector = new GestureDetector(this.getContext(),createNormalModelGesDetctor());
                break;
            case EDIT_MODE:
                //编辑模式下
                //标签可以移动
                setTagsEnableMove(true);

                //点击空白位置，将会添加标签
                gestureDetector = new GestureDetector(this.getContext(),createEditModelGesDetctor());
                break;
            default:
                Log.w(TAG, "there is no corresponding interactive mode while the InteractModel value is " + mInteractModel);
        }
    }

    public ImageView getmImage() {
        return mImage;
    }

    public void setTagsEnableMove(boolean b) {
        mTagsEnableMove = b;
    }

    public boolean ismIsTouchable() {
        return mIsTouchable;
    }

    public void setmIsTouchable(boolean mIsTouchable) {
        this.mIsTouchable = mIsTouchable;
    }

    /**
     * 添加多个标签
     * */
    public void addImgTags(List<ImageTag> imgtags){
        for(ImageTag tags : imgtags){
            this.addImgTag(tags);
        }
    }

    public void addImgTag(ImageTag imgTag){
        addImgTag(imgTag, true);
    }

    /**
     * 添加图片标签
     * 如果isvisible为true，则表示此标签为正常添加的标签，如果为false，则表示此标签为因为翻转而添加的标签
     */
    public void addImgTag(ImageTag imgTag,boolean isVisible) {
        final ImageTagBox tagbox;
        //设置位置
        if(imgTag.getmDir()==0){
            tagbox = (ImageTagBox) LayoutInflater.from(TagableImage.this.getContext()).inflate(R.layout.view_show_tag_item_right, mTagContainer, false);
        }else {
            tagbox = (ImageTagBox) LayoutInflater.from(TagableImage.this.getContext()).inflate(R.layout.view_show_tag_item_left, mTagContainer, false);
        }
        if(!isVisible){
            tagbox.setVisibility(INVISIBLE);
        }
        tagbox.bindImageTag(imgTag);

        //设置点击事件
        tagbox.setmGestureDetector(createDefTagGesDector(tagbox));
        //添加到列表中
        mTags.add(imgTag);
        mTagBoxes.add(tagbox);
        addToTagQueue(tagbox);

        //是否可以移动
        tagbox.setmEnableMove(mTagsEnableMove);
        //触发添加添加标签事件
        if (mOnAddTagBoxListener != null && isVisible) {
            mOnAddTagBoxListener.onAddTagBox(tagbox);
        }
    }

    /**
     * 删除图片标签
     */
    public void delImgTag(ImageTagBox tagBox) {
        mTags.remove(tagBox.getmImgTag());
        mTagBoxes.remove(tagBox);
        mTagContainer.removeView(tagBox);

        if (mOnDelTagBoxListener != null) {
            mOnDelTagBoxListener.onDelTagBox(tagBox);
        }
    }

    /**
     * 删除图片标签
     */
    public void delImgTag(ImageTag imageTag) {
        ImageTagBox box = findTagBoxByTag(imageTag);
        if (box != null) {
            mTagBoxes.remove(box);
            mTagContainer.removeView(box);
        }
        mTags.remove(imageTag);
        if (mOnDelTagBoxListener != null) {
            mOnDelTagBoxListener.onDelTagBox(box);
        }
    }

    /**
     * 删除最后一个标签
     */
    public void delLastImgTag() {
        if (mTagBoxes.size() != 0) {
            delImgTag(mTagBoxes.get(mTagBoxes.size() - 1));
        }
    }

    /**
     * 获取最后一个标签
     */
    public ImageTagBox getLastTagBox() {
        if (mTagBoxes.size() != 0) {
            return mTagBoxes.get(mTagBoxes.size() - 1);
        }
        return null;
    }

    /**
     * 设置背景图片
     * */
    public void setImg(Bitmap bitmap) {
        mBmp = bitmap;
        mImage.setImageBitmap(bitmap);
    }
    public Bitmap getbmp(){
        if(mBmp == null){
            // todo
            //mBmp = ImageTool.
        }
        return mBmp;
    }

    /**
     * 根据标签实例找到标签控件
     */
    public ImageTagBox findTagBoxByTag(ImageTag tag) {
        for (ImageTagBox box : mTagBoxes) {
            if (box.getmImgTag() == tag) {
                return box;
            }
        }
        return null;
    }


    /**
     * 设置内部点击监听接口
     */
    private void setmOnTagClickListener(OnTagClickListener mOnTagClickListener) {
        this.mOnTagClickListener = mOnTagClickListener;
    }

    /**
     * 设置外部点击监听接口
     */
    public void setOnTagClickListener(OnTagClickListener onTagClickListener) {
        this.mOnTagClickListenerOpen = onTagClickListener;
    }

    public void setOnAddTagBoxListener(OnAddTagBoxListener onAddTagBoxListener) {
        mOnAddTagBoxListener = onAddTagBoxListener;
    }

    public void setOnDelTagBoxListener(OnDelTagBoxListener onDelTagBoxListener) {
        mOnDelTagBoxListener = onDelTagBoxListener;
    }




    /**
     * 点击标签控件监听类
     */
    public static interface OnTagClickListener {
        public void onTagClick(ImageTagBox tagBox);
    }

    /**
     * 添加标签控件监听类
     * 在添加之后执行
     */
    public static interface OnAddTagBoxListener {
        public void onAddTagBox(ImageTagBox tagBox);
    }

    /**
     * 删除标签控件监听类
     * 在删除之后执行
     */
    public static interface OnDelTagBoxListener {
        public void onDelTagBox(ImageTagBox tagBox);
    }

    /**普通模式下的事件处理*/
    public  GestureDetector.SimpleOnGestureListener createNormalModelGesDetctor(){
        return new GestureDetector.SimpleOnGestureListener(){
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                //todo 1.点击标签将会跳转到同一标签下，所有图片列表的页面

                //切换标签容器为是否可见
                if (mTagContainer.getVisibility() == VISIBLE) {
                    mTagContainer.setVisibility(GONE);
                } else {
                    mTagContainer.setVisibility(VISIBLE);
                }
                return super.onSingleTapUp(e);
            }
        };
    }

    /**编辑模式下的事件处理*/
    public GestureDetector.SimpleOnGestureListener createEditModelGesDetctor(){
        return new GestureDetector.SimpleOnGestureListener(){
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                if (mIsTouchable) {
                    int x = (int) e.getX();
                    int y = (int) e.getY();

                    //实例化标签bean
                    ImageTag tag = new ImageTag("", "", 0, x * 1f / mTagContainer.getWidth(), y * 1f / mTagContainer.getHeight());
                    //添加标签
                    addImgTag(tag);
                }
                return super.onSingleTapUp(e);
            }
        };
    }

    /**
     * 监听tagbox的点击事件
     * */
    public class TagBoxGestureDetector extends GestureDetector.SimpleOnGestureListener{
        ImageTagBox tagBox;

        public TagBoxGestureDetector(ImageTagBox tagBox) {
            super();
            this.tagBox = tagBox;
        }

    }

    /**
     * 编辑模式下的事件处理器
     * 1.点击标签将会提示是否删除
     * 2.长按则会改变标签方向
     * */
    public  TagBoxGestureDetector createEditModelTagGesDetector(ImageTagBox tagBox){
        return new TagBoxGestureDetector(tagBox){
            @Override
            public void onLongPress(MotionEvent e) {
                //改变标签方向并重新添加
                tagBox.getmImgTag().changeDir();
                TagableImage.this.delImgTag(tagBox);
                TagableImage.this.addImgTag(tagBox.getmImgTag(),false);

                super.onLongPress(e);
            }

            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                //如果tagbox可点击
                if (mIsTouchable) {
                    new AlertDialog.Builder(TagableImage.this.getContext())
                            .setTitle("删除标签")
                            .setMessage("是否删除标签")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //点击确定删除标签
                                    TagableImage.this.delImgTag(tagBox);
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //点击取消则不需要做任何改动
                        }
                    }).show();
                }
                if (mOnTagClickListenerOpen != null) {
                    mOnTagClickListenerOpen.onTagClick(tagBox);
                }
                return super.onSingleTapConfirmed(e);
            }
        };
    }

    /**
     * 创建普通模式下的标签点击监听器
     * 点击标签跳转到某个页面
     */
    public  TagBoxGestureDetector createNormalModelTagGesDetector(ImageTagBox tagBox){
        return new TagBoxGestureDetector(tagBox){
            @Override
            public void onLongPress(MotionEvent e) {
                super.onLongPress(e);
            }

            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                //todo 点击标签跳转到某个页面
                Toast.makeText(TagableImage.this.getContext(), "点击 " + tagBox.getmImgTag().getmText(), Toast.LENGTH_SHORT);
                Log.v(TAG, "onTagClick " + tagBox.getmImgTag().getmText());
                if (mOnTagClickListenerOpen != null) {
                    mOnTagClickListenerOpen.onTagClick(tagBox);
                }
                return super.onSingleTapConfirmed(e);
            }
        };
    }

    public TagBoxGestureDetector createDefTagGesDector(ImageTagBox tagBox){
        if(mInteractModel == EDIT_MODE){
            return createEditModelTagGesDetector(tagBox);
        }else{
            return createNormalModelTagGesDetector(tagBox);
        }
    }
}
